package com.pic4493.app;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.R.integer;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.pic4493.base.BaseUI;
import com.pic4493.comm.PubConst;
import com.pic4493.comm.Session;
import com.pic4493.entities.DJson;
import com.pic4493.entities.EPhoto;
import com.pic4493.net.NetClientJ;
import com.pic4493.utils.UtiDialog;
import com.pic4493.utils.UtiShare;
import com.pic4493.utils.UtiView;
import com.ppcodes.imageloader.core.DisplayImageOptions;
import com.ppcodes.imageloader.core.ImageLoader;
import com.tencent.a.b.l;

public class UIPics extends BaseUI implements OnClickListener
{
   private DisplayImageOptions imgConfig = new DisplayImageOptions.Builder().cacheInMemory().cacheOnDisc().showStubImage(R.drawable.image_loading_big)
		 .showImageForEmptyUri(R.drawable.image_loading_big).bitmapConfig(Bitmap.Config.RGB_565).build();

   private ArrayList<EPhoto> mList;
   private String mAlbumId;
   private String mDescribe;
   private String mNextId;
   private String mNextDescribe;

   private static final String mLastId = "-1";

   /**
    * 从0开始的
    */
   private int mCurrentIndex;
   private int mPicCount;
   private ImageView mImgZan;
   private ImageView mImgShare;
   private ImageView mImgTalk;
   private ImageView mImgFav;
   private ImageView mImgMore;
   private TextView mTxtPageIndex;
   private TextView mTxtPageCount;
   private TextView mTxtContent;
   private TextView mTxtInfoNum;
   private ViewPager mPager;
   private PicAdapter mAdapter;

   private void initView()
   {
	  mPager = (ViewPager) findViewById(R.id.uipics_viewpage);
	  mImgZan = (ImageView) findViewById(R.id.uipics_img_zan);
	  mImgShare = (ImageView) findViewById(R.id.uipics_img_share);
	  mImgTalk = (ImageView) findViewById(R.id.uipics_img_talk);
	  mImgFav = (ImageView) findViewById(R.id.uipics_img_fav);
	  mImgMore = (ImageView) findViewById(R.id.uipics_img_more);
	  mTxtInfoNum = (TextView) findViewById(R.id.uipics_txt_infonum);
	  mTxtPageIndex = (TextView) findViewById(R.id.uipics_txt_pageindex);
	  mTxtPageCount = (TextView) findViewById(R.id.uipics_txt_pagecount);
	  mTxtContent = (TextView) findViewById(R.id.uipics_txt_content);
	  mTxtInfoNum = (TextView) findViewById(R.id.uipics_txt_infonum);
   }

   private void initEvent()
   {
	  mImgZan.setOnClickListener(this);
	  mImgShare.setOnClickListener(this);
	  mImgTalk.setOnClickListener(this);
	  mImgFav.setOnClickListener(this);
	  mImgMore.setOnClickListener(this);
	  mPager.setOnPageChangeListener(new OnPageChangeListener()
	  {
		 @Override
		 public void onPageSelected(int position)
		 {
			if (position == (mList.size() - 1))
			{
               loadData(true);
			}
			else
			{
			   mCurrentIndex = position;
			   mTxtPageIndex.setText(String.valueOf(position + 1));
			   setFav();
//			   if (Integer.valueOf(mList.get(position).getComment()) > 0)
//			   {
//				  mTxtInfoNum.setVisibility(View.VISIBLE);
//				  mTxtInfoNum.setText(mList.get(position).getComment());
//			   }
//			   else
//			   {
//				  mTxtInfoNum.setVisibility(View.INVISIBLE);
//			   }
			}
		 }

		 @Override
		 public void onPageScrolled(int arg0, float arg1, int arg2)
		 {
		 }

		 @Override
		 public void onPageScrollStateChanged(int position)
		 {
		 }
	  });
   }

   private void loadData(boolean isNext)
   {
	  mCurrentIndex=0;
	  mPicCount=0;

	  if(!isNext)
	  {
		 executeAsyncTask("loadData",new Object[]{mAlbumId});	
		 mTxtContent.setText(mDescribe);
	  }
	  else
	  {
		 executeAsyncTask("loadData",new Object[]{mNextId});
		 mTxtContent.setText(mNextDescribe);
	  }
   }

   @Override
   protected void onCreate(Bundle savedInstanceState)
   {
	  setContentView(R.layout.uipics);
	  super.onCreate(savedInstanceState);

	  mAlbumId = getIntent().getStringExtra(PubConst.Intent_Key.AlbumId);
	  mDescribe = getIntent().getStringExtra(PubConst.Intent_Key.Describe);

	  initView();
	  initEvent();

	  loadData(false);
   }

   private void setFav()
   {
	  if (mList.get(mCurrentIndex).isCollected())
	  {
		 mImgFav.setImageResource(R.drawable.btn_pics_fav_opposite);
	  }
	  else
	  {
		 mImgFav.setImageResource(R.drawable.btn_pics_fav);
	  }
   }

   @Override
   public void onClick(View v)
   {
	  Intent uiIntent = new Intent();
	  switch (v.getId())
	  {
		 case R.id.uipics_img_zan:// 点赞
			executeAsyncTask("zan");
			break;

		 case R.id.uipics_img_share:// 分享
			UtiShare.share(mContext, mList.get(mCurrentIndex).getUrl());
			break;

		 case R.id.uipics_img_talk:// 评论
			uiIntent.setClass(mContext, UIPicReview.class);
			uiIntent.putExtra(PubConst.Intent_Key.AlbumId, mAlbumId);
			startActivity(uiIntent);
			break;

		 case R.id.uipics_img_fav:// 收藏
			if (Session.getInstance().isLogin())
			{
			   if (mList.get(mCurrentIndex).isCollected())
			   {
				  executeAsyncTask("unfav");
			   }
			   else
			   {
				  executeAsyncTask("fav");
			   }
			}
			else
			{
			   uiIntent.setClass(mContext, UISignUp.class);
			   startActivityForResult(uiIntent, PubConst.ActivityJump.LOGIN);
			}
			break;

		 case R.id.uipics_img_more:// 更多
			uiIntent.setClass(mContext, UISetting.class);
			startActivity(uiIntent);
			break;
	  }
   }

   @Override
   public void onAsyncTaskStart(String taskName, Object[] params)
   {
	  UtiDialog.getInstance().ShowLoadingDialogNoTitleEX(mContext, "请稍候...");
   }

   @Override
   public Object onAsyncTaskInBackground(String taskName, Object[] params) throws Exception
   {
	  if ("zan".equals(taskName))
	  {
		 return NetClientJ.Zan(mList.get(mCurrentIndex).getId());
	  }
	  else if ("fav".equals(taskName))
	  {
		 return NetClientJ.AddToFavorites(mList.get(mCurrentIndex).getId());
	  }
	  else if ("unfav".equals(taskName))
	  {
		 return NetClientJ.DeleteFromFavorites(mList.get(mCurrentIndex).getId());
	  }
	  else if ("loadData".equals(taskName))
	  {
		 return NetClientJ.GetPhotosByAlbumId(params[0].toString());
	  }
	  return null;
   }

   @Override
   public void onAsyncTaskEnd(String taskId, String taskName, Object[] params, Object result)
   {
	  UtiDialog.getInstance().DismissLoadingDialog();
	  try
	  {
		 if (result != null)
		 {
			DJson data = (DJson) result;
			if (!data.getHead().hasError())
			{
			   if ("zan".equals(taskName))
			   {
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "你赞了这张图片");
				  return;
			   }
			   else if ("fav".equals(taskName))
			   {
				  // 收藏成功更新本地数据
				  EPhoto photo = mList.get(mCurrentIndex);
				  photo.setCollect("1");
				  mList.set(mCurrentIndex, photo);
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "收藏成功");
				  setFav();
				  return;
			   }
			   else if ("unfav".equals(taskName))
			   {
				  // 取消收藏成功更新本地数据
				  EPhoto photo = mList.get(mCurrentIndex);
				  photo.setCollect("0");
				  mList.set(mCurrentIndex, photo);
				  UtiDialog.getInstance().ShowToastInfoShort(mContext, "取消收藏成功");
				  setFav();
				  return;
			   }
			   else if ("loadData".equals(taskName))
			   {
				  JSONObject object = data.getBody();

				  mNextId = object.optString("nextAid");//下一部相册ID
				  mNextDescribe=object.optString("nextName");//下一步相册名称

				  JSONArray photos = object.optJSONArray("pics");

				  EPhoto photo = null;

				  if (photos != null)
				  {
					 mList = new ArrayList<EPhoto>();
					 for (int i = 0; i < photos.length(); i++)
					 {
						photo = new EPhoto();
						photo.setId(photos.optJSONObject(i).optString("pid"));
						photo.setAlbumId(photos.optJSONObject(i).optString("aid"));
						photo.setClickCount(photos.optJSONObject(i).optString("click"));
						photo.setComment(photos.optJSONObject(i).optString("comment"));
						photo.setUrl(photos.optJSONObject(i).optString("pic"));
						photo.setZanNum(photos.optJSONObject(i).optString("praise"));
						photo.setCollect(photos.optJSONObject(i).optString("collect"));
						mList.add(photo);
					 }

					 photo = new EPhoto();
					 photo.setId(mLastId);
					 mList.add(photo);

					 mAdapter = new PicAdapter();
					 mPager.setAdapter(mAdapter);

					 mPicCount = mList.size();
					 mTxtPageIndex.setText("1");
					 mTxtPageCount.setText(String.valueOf(mPicCount-1));
					 setFav();
				  }
				  else
				  {
					 if (mList.size() == 0)
					 {
						UtiDialog.getInstance().ShowToastInfoShort(mContext, "暂无数据");
						finish();
					 }
				  }
			   }
			}
			else
			{
			   UtiDialog.getInstance().ShowToastInfoShort(mContext, data.getHead().getRspMsg());
			}
		 }
		 else
		 {
			UtiDialog.getInstance().ShowToastInfoShort(mContext, "网络异常请稍候再试");
		 }
	  }
	  catch (Exception e)
	  {
		 Log.d("ERROR", "UIPics_onAsyncTaskEnd(taskId, taskName, params, result) " + e);
	  }
   }

   private class PicAdapter extends PagerAdapter
   {
	  @Override
	  public int getCount()
	  {
		 return mList.size();
	  }

	  @Override
	  public Object instantiateItem(View collection, int position)
	  {
		 View view = getLayoutInflater().inflate(R.layout.uipics_page_item, null);
		 if (position < (mList.size() - 1))
		 {
			ImageView imageView = (ImageView) view.findViewById(R.id.uipics_page_item_img);
			UtiView.registerDoubleClickListener(imageView, new UtiView.OnDoubleClickListener()
			{
			   @Override
			   public void OnSingleClick(View v)
			   {
			   }

			   @Override
			   public void OnDoubleClick(View v)
			   {
				  Session.getInstance().picCache = ((BitmapDrawable) ((ImageView) v).getDrawable()).getBitmap();
				  Intent intent = new Intent(mContext, UIPic.class);
				  startActivity(intent);
			   }
			});
			ImageLoader.getInstance().displayImage(mList.get(position).getUrl(), imageView, imgConfig);
			((ViewPager) collection).addView(view, 0);
		 }

		 return view;
	  }

	  @Override
	  public void destroyItem(View collection, int position, Object view)
	  {
		 ((ViewPager) collection).removeView((View) view);
	  }

	  @Override
	  public boolean isViewFromObject(View view, Object object)
	  {
		 return view.equals(object);
	  }

	  @Override
	  public void finishUpdate(View arg0)
	  {
	  }

	  @Override
	  public void restoreState(Parcelable arg0, ClassLoader arg1)
	  {
	  }

	  @Override
	  public Parcelable saveState()
	  {
		 return null;
	  }

	  @Override
	  public void startUpdate(View arg0)
	  {
	  }
   }
}
